﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace si.caha.Repository
{
    /// <summary>
    /// Class base functionality of repositories
    /// </summary>
    public class BaseRepository
    {
        public BaseRepository(DataContext dataContext)
        {
            this.dataContext = dataContext;
        }
        
        private readonly DataContext dataContext;
        protected DataContext GetDataContext()
        {
            return this.dataContext;
        }
        
        private List<ValidationResult> ValidateEntity(object entity)
        {
            List<ValidationResult> validationResults = new List<ValidationResult>();
            ValidationContext valContext = new ValidationContext(entity, null, null);
            // validate all properties of entity
            Validator.TryValidateObject(entity, valContext, validationResults, true);
            return validationResults;
        }

        /**
         *  This method is adding name of database fields and errors into dictionary.
         *  Example:
         *      We have an entity of class Item, which have a property named Title 
         *      at which validation doesn't go through. User input is too loong.
         *      Then method returns Dictionary<String, String> 
         *      with values "Title", "String too loong" or whatever annotation message 
         *      is defined in entity class.
         */
        protected Dictionary<string, string> ValidateAndGetErrors(object entity)
        {
            List<ValidationResult> validationResults = ValidateEntity(entity);
            Dictionary<string, string> errors = new Dictionary<string, string>();
            foreach (ValidationResult vr in validationResults)
            {
                errors.Add(vr.MemberNames.ElementAt(0).ToString(), vr.ErrorMessage);
            }
            return errors;
        }
    }
}